package com.taotao.job.rpc.core.invoker;

import com.google.common.base.Preconditions;
import com.taotao.job.rpc.core.utils.StringUtils;
import com.taotao.job.rpc.invoker.AddressedRemoteInvoker;
import com.taotao.job.rpc.invoker.caller.RemoteCaller;
import com.taotao.job.rpc.sofabolt.SofaboltRemoteCaller;

import java.util.concurrent.ConcurrentHashMap;

/**
 * @author fanbeibei
 * @date 2021/4/6 23:29
 */
public class RemoteInvokerFactory {
    private final ConcurrentHashMap<String, AddressedRemoteInvoker> addressedRemoteInvokerCache = new ConcurrentHashMap<>();

    public AddressedRemoteInvoker newAddressedRemoteInvoker(String address) {
        return newAddressedRemoteInvoker(address, new SofaboltRemoteCaller());
    }

    public AddressedRemoteInvoker newAddressedRemoteInvoker(String address, RemoteCaller remoteCaller) {
        Preconditions.checkArgument(StringUtils.isNotBlank(address));
        Preconditions.checkArgument(null != remoteCaller);

        AddressedRemoteInvoker invoker = addressedRemoteInvokerCache.get(address);
        if (null == invoker) {
            synchronized (this) {
                if (null == invoker) {
                    invoker = new AddressedRemoteInvoker(remoteCaller, address);
                    addressedRemoteInvokerCache.putIfAbsent(address, invoker);
                }
            }
        }

        return invoker;
    }

}
